import * as types from '@/store/mutation-types';
import router from '@/router';
import { getMenu, placeOrderRequest } from '@/request/menu';
import { get } from '@/common/utils';

import _ from 'lodash';

export default {
  async getMenuList({ commit }, id) {
    //* 显示loding
    commit(types.SHOW_LOADING);
    try {
      const result = await getMenu(id);
      console.log(result);
      commit(types.SAVE_MENU_CATEGORIES, { categories: result.categories });
      commit(types.SAVE_MENU_FOOD, { foods: result.foods });
    } catch (error) {
      console.log('erro======>', error);
    } finally {
      // * 最终移除loading
      commit(types.HIDE_LOADING);
    }
  },

  // 下单
  async placeOrder({ commit }, id) {
    //* 显示loding
    commit(types.SHOW_LOADING);
    try {
      const payment = get('payment');
      const cart = get(id);
      const user = get('user');
      const userId = _.get(user, '_id');
      const result = await placeOrderRequest({
        payment,
        cart,
        userId,
        restaurantId: id,
        token: user.token,
      });
      console.log('result=====', result);
      localStorage.removeItem(id);
      commit(types.GET_ORDER_LIST_STATE, { orderListState: [] });
      router.push('/order');
    } catch (error) {
      console.log('erro======111>', error);
      const { message } = error;
      commit(types.SHOW_ALERT, {
        message,
        func: () => { router.push('/login'); },
      });
    } finally {
      // * 最终移除loading
      commit(types.HIDE_LOADING);
    }
  },
  saveFoodsList({ commit }, { list }) {
    commit(types.SAVE_FOODS_LIST, { foodsList: list });
  },

  //* 从local storage 中拿点餐列表
  getOrderListState({ commit }, { id }) {
    const result = get(id);

    if (result) {
      commit(types.GET_ORDER_LIST_STATE, { orderListState: result });
    }
  },
  // 清除点餐列表
  cleanOrderListState({ commit }) {
    commit(types.GET_ORDER_LIST_STATE, { orderListState: [] });
  },
  saveShowCard({ commit }, { list }) {
    commit(types.SAVE_SHOW_CARD_LIST, { showCardList: list });
  },
};
